<?php

namespace common\components;
use yii\base\Component;

/**
 * 无限极分类-二维无限分类数组处理类
 **/

class Category extends Component
{



    static function getTree($list, $pid = 0)
    {
        $tree = [];
        if (!empty($list)) {        //先修改为以id为下标的列表
            $newList = [];
            foreach ($list as $k => $v) {
                $newList[$v['id']] = $v;
            }        //然后开始组装成特殊格式
            foreach ($newList as $value) {
                if ($pid == $value['parentid']) {//先取出顶级
                    $tree[] = &$newList[$value['id']];
                } elseif (isset($newList[$value['parentid']])) {//再判定非顶级的pid是否存在，如果存在，则再pid所在的数组下面加入一个字段items，来将本身存进去
                    $newList[$value['parentid']]['items'][] = &$newList[$value['id']];
                }
            }
        }
        return $tree;
    }


    /**
     * @param $list
     * @param $pid
     * 获取直接子类
     */
    public static function getSon($list,$pid=[],$aa=false){

        foreach ($pid as $k => $r){
            foreach ($list as $key => $row){
                if($row['parentid'] == $r){
                    if($aa){
                        $rows[self::getParent($list,$r)['name']] = $row;
                    }
                    $rows[] = $row;
                }
            }
        }
        return $rows;
    }


    public static function getParent($list,$pid)
    {
        foreach ($list as $key => $row){
            if($row['id'] == $pid){
                return $row;
            }
        }

    }






}